package com.example.a2207_zh.fragment

import android.content.DialogInterface
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AlertDialog
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.example.a2207_zh.R
import com.example.a2207_zh.adapter.VideoMimeAdapter
import com.example.a2207_zh.database.AppDBUtils
import com.example.a2207_zh.databinding.FragmentMineBinding
import com.example.a2207_zh.entity.VideoEntity
import com.example.a2207_zh.mvvm.BaseViewFragment

class MineFragment : BaseViewFragment<FragmentMineBinding>() {
    val list = mutableListOf<VideoEntity>()
    lateinit var videoMimeAdapter: VideoMimeAdapter
    override fun getLayout(): Int  = R.layout.fragment_mine

    override fun initView() {
        videoMimeAdapter = VideoMimeAdapter(list)
        binding.rv.adapter = videoMimeAdapter
        binding.rv.layoutManager = StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL)//瀑布流布局

        val data = AppDBUtils.getDb().getVideoDao().queryVideo()
        list.clear()
        list.addAll(data)
        videoMimeAdapter.notifyDataSetChanged()

        //长按item，弹出提示框，确定后删除
        videoMimeAdapter.setOnItemLongClickListener { adapter, view, position ->

            AlertDialog.Builder(requireContext())
                .setIcon(R.mipmap.ic_launcher)
                .setTitle("提示")
                .setMessage("确定删除吗")
                .setPositiveButton("确定",object :DialogInterface.OnClickListener{
                    override fun onClick(dialog: DialogInterface?, which: Int) {
                        //先删除后台---数据库
                        AppDBUtils.getDb().getVideoDao().deleteVideo(list[position])
                        //删除页面
                        list.removeAt(position)
                        videoMimeAdapter.notifyDataSetChanged()
                    }
                })
                .setNegativeButton("取消"
                ) { dialog, which -> }
                .create()
                .show()

            return@setOnItemLongClickListener true //返回true 不会触发点击item事件
        }

    }

    override fun initData() {

    }

}